package com.jsh.erp.service.user;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.JshUserChangeMapper;
import com.jsh.erp.service.ICommonQuery;
import com.jsh.erp.service.ISysDepartService;
import com.jsh.erp.service.ISysRoleService;
import com.jsh.erp.service.ISysUserService;
import com.jsh.erp.utils.Constants;
import com.jsh.erp.utils.QueryUtils;
import com.jsh.erp.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;


import com.jsh.common.system.vo.LoginUser;
import com.jsh.modules.activiti.entity.SysDepart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service(value = "user_component")
@UserResource
@Slf4j
public class UserComponent implements ICommonQuery {

    @Resource
    private UserService userService;

    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private JshUserChangeMapper jshUserChangeMapper;
    @Autowired
    private ISysDepartService iSysDepartService;
    @Autowired
    private ISysRoleService iSysRoleService;


    @Override
    public Object selectOne(Long id) throws Exception {
        return userService.getUser(id);
    }

    @Override
    public List<?> select(Map<String, String> map) throws Exception {
        return getUserList(map);
    }

    private List<?> getUserList(Map<String, String> map) throws Exception {
        String search = map.get(Constants.SEARCH);
        String userName = StringUtil.getInfo(search, "userName");
        String loginName = StringUtil.getInfo(search, "loginName");
        String order = QueryUtils.order(map);
        String filter = QueryUtils.filter(map);
        return userService.select(userName, loginName, QueryUtils.offset(map), QueryUtils.rows(map));

    }

    @Override
    public Long counts(Map<String, String> map) throws Exception {
        String search = map.get(Constants.SEARCH);
        String userName = StringUtil.getInfo(search, "userName");
        String loginName = StringUtil.getInfo(search, "loginName");
        return userService.countUser(userName, loginName);
    }

    @Override

    public int insert(JSONObject obj, HttpServletRequest request) throws Exception {
        //由于jeecg用户id类型跟erp用户类型不一样  新建用户时要新建jeecg用户  以及erp系统用户关联表
        UserEx userEx = JSONObject.parseObject(obj.toJSONString(), UserEx.class);

        Subject subject = SecurityUtils.getSubject();
        boolean b = subject.hasRole("admin") || subject.hasRole("adminDown");
        if (!b) {
            //没有管理员权限
            return -1;
        }
            //添加jeecg user用户
            SysUser sysUser = JSONObject.parseObject(obj.toJSONString(), SysUser.class);

            boolean save = iSysUserService.save(sysUser);
        if (!save) {
            return -0;
        }

        String id = sysUser.getId();//新增jeecg 用户的id
        JshUserChange jshUserChange = new JshUserChange();
        jshUserChange.setJeecgUserId(id);

        //添加erp  user用户
        UserEx userEx1 = userService.addUser(userEx);
        Long id1 = userEx1.getId();//新增erp 用户的id

        //添加erp  jeecg用户的关联表
        jshUserChange.setErpUserId(id1.intValue());
        int insert = jshUserChangeMapper.insert(jshUserChange);

        if (save && insert > 0) {
            return 1;
        } else {
            log.error("新增用户失败  新增jeecg用户 " + save + "  erp系统用户关联表" + (insert > 0 ? true : false));
            return 0;
        }
    }

    @Override
    public int update(JSONObject obj, HttpServletRequest request) throws Exception {
        //修改jeecg用户以及erp用户即可 erp jeecg关联表不会变化
        SysUser sysUser = JSONObject.parseObject(obj.toJSONString(), SysUser.class);

        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<SysUser>()
                .eq("id", sysUser.getId())
                .setEntity(sysUser).setEntityClass(SysUser.class);

        //是否修改成功
        boolean update = iSysUserService.update(updateWrapper);

        //查询对应的erp user
        JshUserChange jeecg_user_id = jshUserChangeMapper.selectOne(new QueryWrapper<JshUserChange>().eq("jeecg_user_id", sysUser.getId()));
        Integer erpUserId = jeecg_user_id.getErpUserId();

        UserEx userEx = new UserEx();
        userEx.setUsername(sysUser.getUsername());
        userEx.setPassword(sysUser.getPassword());
        userEx.setRoleName(sysUser.getRealname());
        userEx.setEmail(sysUser.getEmail());
        userEx.setId(Long.valueOf(erpUserId));
        UserEx userEx1 = userService.updateUser(userEx);
        if (update&&userEx1!=null) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public int delete(Long erpId, HttpServletRequest request) throws Exception {
        //查询系统用户关联表
        QueryWrapper<JshUserChange> erp_user_id = new QueryWrapper<JshUserChange>().eq("erp_user_id", erpId);
        JshUserChange jshUserChange = jshUserChangeMapper.selectOne(erp_user_id);


        if (jshUserChange == null) {
            log.error("erp系统用户关联表缺失  具体缺失为:erp_user_id:  " + erpId);
            return 0;
        }
        String jeecgUserId = jshUserChange.getJeecgUserId();
        SysUser sysUserById = iSysUserService.getById(jeecgUserId);
        if (sysUserById == null) {
            log.error("erp系统用户关联表表达了错误的关系  具体错误为:erp_user_id:  " + erpId + "对应jeecgUserId 用户不存在");
            return 0;
        }

        //要删除的用户id
        String id = jshUserChange.getJeecgUserId();


        //查看当前的操作用户是谁
        Subject subject = SecurityUtils.getSubject();
        LoginUser loginUser = (LoginUser) subject.getPrincipal();
        String userId = loginUser.getId();
        if (userId.equals(id)) {
            return 0;
        }
        boolean admin = subject.hasRole("admin");
        if (admin) {
            //确定要删除的用户是什么角色
            SysRole sysRole = iSysRoleService.findRolebyUserId(id);
            String roleCode = sysRole.getRoleCode();
            if (org.apache.commons.lang.StringUtils.equals(roleCode, "admin")) {
                return 0;
            }
            //超级管理员权限 任何都能删
            iSysUserService.deleteUser(id);
            //删除对应表
            QueryWrapper<JshUserChange> del = new QueryWrapper<JshUserChange>().eq("jeecg_user_id", id);
            jshUserChangeMapper.delete(del);
            return 1;
        }
        boolean adminDown = subject.hasRole("adminDown");
        if (adminDown) {
            //管理员权限 除了超级管理员都能删
            //确定要删除的用户是什么角色
            SysRole sysRole = iSysRoleService.findRolebyUserId(id);
            String roleCode = sysRole.getRoleCode();
            if (org.apache.commons.lang.StringUtils.equals(roleCode, "admin") || org.apache.commons.lang.StringUtils.equals(roleCode, "adminDown")) {
                return 0;
            }
            iSysUserService.deleteUser(id);
            //删除对应表
            QueryWrapper<JshUserChange> del = new QueryWrapper<JshUserChange>().eq("jeecg_user_id", id);
            jshUserChangeMapper.delete(del);
            return 1;
        }
        boolean manage = subject.hasRole("manage");
        if (manage) {
            //管理者角色  只能删除本部门的用户 且不能删除自己的父级用户  以及被admin adminDown创建的用户
            SysRole sysRole = iSysRoleService.findRolebyUserId(id);
            String roleCode = sysRole.getRoleCode();
            if (org.apache.commons.lang.StringUtils.equals(roleCode, "manage") || org.apache.commons.lang.StringUtils.equals(roleCode, "employee")) {
                //同级或下级权限
                //核对是否自己部门的
                List<SysDepart> sysDeparts = iSysDepartService.findDepartsByUserId(id);//删除的user部门
                List<SysDepart> userSysDeparts = iSysDepartService.findDepartsByUserId(userId);//当前操作的user部门


                if (sysDeparts.size() == 0 || userSysDeparts.size() == 0) {
                    return 0;
                }
                sysDeparts.removeAll(userSysDeparts);
                if (sysDeparts.size() > 0) {
                    return 0;
                }
                //确定是否父级用户
                Boolean flag = iSysUserService.isParent(userId, id);
                if (flag) {
                    //父级用户
                    return 0;
                }

                SysUser byId = iSysUserService.getById(id);

                if (byId.getCreateBy().equals("admin") || byId.getCreateBy().equals("adminDown")) {
                    //管理员创建的用户
                    return 0;
                }

                iSysUserService.deleteUser(id);
                //删除对应表
                QueryWrapper<JshUserChange> del = new QueryWrapper<JshUserChange>().eq("jeecg_user_id", id);
                jshUserChangeMapper.delete(del);
                return 1;
            }
        }
        return 0;
    }

    @Override
    public int deleteBatch(String ids, HttpServletRequest request) throws Exception {
        //批量删除
        String[] split = ids.split(",");
        for (String s : split) {
            int delete = this.delete(Long.valueOf(s), null);
        }

        return 1;
    }

    @Override
    public int checkIsNameExist(Long id, String name) throws Exception {
        //name是否存在
        JshUserChange erp_user_id = jshUserChangeMapper.selectOne(new QueryWrapper<JshUserChange>().eq("erp_user_id", id));
        if(erp_user_id==null){
            return 0;
        }

        Integer count = iSysUserService.checkIsNameExist(erp_user_id.getId(),name);
        return count;
    }

}
